/**
 * @(#)PayLogController.java 2017年7月7日
 * Copyright(C) 2017年7月7日 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.mq.KafkaMqManager;
import org.jsbd.boss.mq.MqLogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.webnion.log.api.bean.DbTaskBean;

/**
 * 公共日志保存接口
 * 
 * @author <a href="mailto:zhouchao@zhexinit.com" >周超</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping("/common/log")
public class CommonLogController {

	public static final Logger LOGGER = LoggerFactory.getLogger(CommonLogController.class);


	@RequestMapping(value = "save")
	@ResponseBody
	public Map<String, Object> save(DbTaskBean task) {
		KafkaMqManager.saveLogToQueue(JSON.toJSONString(task));
		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "/sdk/save")
	@ResponseBody
	public Map<String, Object> sdkLogSave(HttpServletRequest request, HttpServletResponse resp) {
		String logs=getLogData(request);
		if(StringUtils.isBlank(logs)) {
			return ResponseMapUtils.responseFail();
		}
		
		try {
			JSONArray logArr=JSON.parseArray(logs);
			for(int i=0;i<logArr.size();i++) {
				JSONObject json=logArr.getJSONObject(i);
				MqLogManager.saveSdkLog(json.toJSONString());
			}
			return ResponseMapUtils.responseSuccess();
		}catch(Exception e) {
			LOGGER.error("解析json报错[{}]",logs);
		}
		return ResponseMapUtils.responseFail();
	}

	private String getLogData(HttpServletRequest request) {
		InputStream in=null;
		try {
			byte[] data=IOUtils.toByteArray(request.getInputStream());
			return new String(data,"UTF-8");
		} catch (IOException e) {
			LOGGER.error("获取sdk日志报错",e);
		}finally {
			if(in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					LOGGER.error("",e);
				}
			}
		}
		return null;
	}
	

}
